/*
 * author      : dormi330
 * date        : 2018/6/26
 * description : 工具类
 */

package com.deep.trade.common;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.beanutils.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CommonUtils {

    private static final String BLANK_STRING = "";

    public static String defaultIfNull(String srcStr, String defaultStr) {
        return null == srcStr ? defaultStr : srcStr;
    }

    // 获取uuid, 目前采用java自带的uuid
    public static String uuid() {
        return UUID.randomUUID().toString().substring(0, 32).replace("-", "");
    }

    public static String currentClassAndMethod() {
        final StackTraceElement e = Thread.currentThread().getStackTrace()[2];
        final String s = e.getClassName();
        return s.substring(s.lastIndexOf('.') + 1, s.length()) + "." + e.getMethodName();
    }

    public static String objectToJson(Object obj) {
        // pretty
        // Gson gson = new GsonBuilder().setPrettyPrinting(s).create();
        // return gson.toJson(obj);

        // plain 版本
        return new Gson().toJson(obj);
    }

    public static <T> T fromJsonString(String json, Class<T> type) {
        if (null == json) return null;
        return new Gson().fromJson(json, type);
    }

    public static <T> String list2String(List<T> list) {
        return new Gson().toJson(list);
    }

    public static boolean stringNotBlankAndNull(String s) {
        return !(null == s || BLANK_STRING.equals(s));
    }

    public static <T, R> List<R> entity2Dto(List<T> entityList, Class<R> dtoClazz) throws Exception {
        List<R> list = new ArrayList<>(entityList.size());
        for (T sourceItem : entityList) {
            R destDto = dtoClazz.newInstance();
            BeanUtils.copyProperties(destDto, sourceItem);
            list.add(destDto);
        }
        return list;
    }

    public static <T, R> PageInfo<R> entity2Dto(PageInfo<T> pageInfo, Class<R> dtoClazz) throws Exception {
        List<R> listDest = entity2Dto(pageInfo.getList(), dtoClazz);

        PageInfo<R> pageInfo2 = new PageInfo<>();
        BeanUtils.copyProperties(pageInfo2, pageInfo);
        pageInfo2.setList(listDest);

        return pageInfo2;
    }

//    public static Map<String, String> jsonString2Map(String json) {
//        Type type = new TypeToken<Map<String, String>>() {
//        }.getType();
//        Map<String, String> myMap = new Gson().fromJson(json, type);
//        return myMap;
//    }


    public static JsonObject fromString(String json) {
        return new Gson().fromJson(json, JsonObject.class);
    }


}
